<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { fetchAddOrder, fetchEditOrder } from '@/service/api';
import { $t } from '@/locales';
import { localStg } from '@/utils/storage';
// import { enableStatusOptions, userGenderOptions } from '@/constants/business';

defineOptions({
  name: 'UserOperateModel'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Food.Order | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增订单',
    edit: '编辑订单'
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.Food.Order,
  | 'desk'
  | 'price'
  | 'afterprice'
  | 'sale'
  | 'customer'
  | 'waiter'
  | 'current'
  | 'description'
  | 'message'
  | 'gorilla.csrf.Token'
>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    desk: '1号桌',
    price: 0,
    afterprice: 0,
    sale: 1,
    customer: '',
    waiter: '',
    current: '进行中',
    description: '',
    message: ''
  };
}

type RuleKey = Extract<keyof Model, 'userName' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  userName: defaultRequiredRule,
  status: defaultRequiredRule
};

/** the enabled role options */
const roleOptions = ref<CommonType.Option<string>[]>([]);

function getRoleOptions() {
  roleOptions.value = [
    {
      label: '进行中',
      value: '进行中'
    },
    {
      label: '点单完成等待上菜',
      value: '点单完成等待上菜'
    },
    {
      label: '已结账',
      value: '已结账'
    }
  ];
}

const deskOptions = ref<CommonType.Option<string>[]>([]);

function getDeskOptions() {
  deskOptions.value = [
    {
      label: '1号桌',
      value: '1号桌'
    },
    {
      label: '2号桌',
      value: '2号桌'
    },
    {
      label: '3号桌',
      value: '3号桌'
    },
    {
      label: '4号桌',
      value: '4号桌'
    },
    {
      label: '5号桌',
      value: '5号桌'
    },
    {
      label: '6号桌',
      value: '6号桌'
    },
    {
      label: '7号桌',
      value: '7号桌'
    },
    {
      label: '8号桌',
      value: '8号桌'
    },
    {
      label: '9号桌',
      value: '9号桌'
    },
    {
      label: '10号桌',
      value: '10号桌'
    },
    {
      label: '11号桌',
      value: '11号桌'
    },
    {
      label: '12号桌',
      value: '12号桌'
    },
    {
      label: '13号桌',
      value: '13号桌'
    },
    {
      label: '14号桌',
      value: '14号桌'
    },
    {
      label: '15号桌',
      value: '15号桌'
    },
    {
      label: '16号桌',
      value: '16号桌'
    },
    {
      label: '17号桌',
      value: '17号桌'
    },
    {
      label: '18号桌',
      value: '18号桌'
    }
  ];
}

// async function getRoleOptions() {
//   const { error, data } = await fetchGetAllRoles();

//   if (!error) {
//     const options = data.map(item => ({
//       label: item.roleName,
//       value: item.roleCode
//     }));

//     // the mock data does not have the roleCode, so fill it
//     // if the real request, remove the following code
//     const userRoleOptions = model.userRoles.map(item => ({
//       label: item,
//       value: item
//     }));
//     // end

//     roleOptions.value = [...userRoleOptions, ...options];
//   }
// }

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  console.log('csrf model', localStg.get('csrf'));
  model['gorilla.csrf.Token'] = localStg.get('csrf') || '';
  // request
  if (props.operateType === 'add') {
    const { error, data } = await fetchAddOrder(model);
    if (!error) {
      // Object.assign(model, data);
      // return;
      console.log('success', data);
      window.$message?.success('新增成功');
    } else {
      console.log('error', error, data);
      window.$message?.error(error?.response?.data.msg);
    }
  }

  if (props.operateType === 'edit') {
    const { error, data } = await fetchEditOrder(model.id, model);
    if (!error) {
      // Object.assign(model, data);
      // return;
      console.log('success', data);
      window.$message?.success($t('common.updateSuccess'));
    } else {
      console.log('error', error);
      window.$message?.error(error?.response?.data.msg);
    }
  }

  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
    getRoleOptions();
    getDeskOptions();
  }
});
</script>

<template>
  <NModal v-model:show="visible">
    <NCard :title="title">
      <NForm ref="formRef" :model="model" :rules="rules" size="large" label-placement="top">
        <NGrid :cols="24" :x-gap="24">
          <NFormItemGi :span="12" :label="$t('page.food.order.desk')" path="desk">
            <NSelect v-model:value="model.desk" :options="deskOptions" filterable placeholder="请选择状态" />
          </NFormItemGi>
          <NFormItemGi :span="12" :label="$t('page.food.order.current')" path="current">
            <NSelect v-model:value="model.current" :options="roleOptions" placeholder="请选择状态" />
          </NFormItemGi>
          <NFormItemGi :span="8" :label="$t('page.food.order.price')" path="price">
            <NRadioGroup v-model:value="model.price">
              <NInputNumber v-model:value="model.price" :precision="2" />
            </NRadioGroup>
          </NFormItemGi>
          <NFormItemGi :span="8" :label="$t('page.food.order.afterprice')" path="afterprice">
            <NInputNumber v-model:value="model.afterprice" placeholder="打折后的价格" clearable :precision="2" />
          </NFormItemGi>
          <NFormItemGi :span="8" :label="$t('page.food.order.sale')" path="sale">
            <NInputNumber v-model:value="model.sale" placeholder="折扣" clearable :precision="2" />
          </NFormItemGi>
          <NFormItemGi :span="12" :label="$t('page.food.order.customer')" path="customer">
            <NInput v-model:value="model.customer" placeholder="顾客" />
          </NFormItemGi>
          <NFormItemGi :span="12" :label="$t('page.food.order.waiter')" path="waiter">
            <NInput v-model:value="model.waiter" placeholder="服务员" />
          </NFormItemGi>
          <NFormItemGi :span="12" :label="$t('page.food.order.description')" path="description">
            <NInput v-model:value="model.description" placeholder="描述" />
          </NFormItemGi>
          <NFormItemGi :span="12" :label="$t('page.food.order.message')" path="message">
            <NInput v-model:value="model.message" placeholder="备注" />
          </NFormItemGi>
        </NGrid>
      </NForm>

      <template #footer>
        <NSpace justify="space-around" size="large" :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NCard>
  </NModal>
</template>

<style scoped></style>
